<template>
  <el-select
      v-model="computedUserId"
      filterable
      remote
      reserve-keyword
      placeholder="请输入关键词"
      :remote-method="loadUsers"
      :loading="loading"
  >
    <el-option
        v-for="item in userList"
        :key="item.userId"
        :label="item.nickName"
        :value="item.userId"
    />
    <el-option v-if="finish" disabled label="没有更多了" value="xxx"/>
    <el-button v-else @click="loadUsers('')">下一页</el-button>
  </el-select>
</template>

<script lang="ts" setup>
import {computed, reactive, ref} from "vue";
import {User} from "@/typings";
import {listUser} from "@/api/system/user";

const props = defineProps({userId: {type: String, default: ''}})
const emits = defineEmits(['update:userId'])

let finish = ref(false)
let loading = ref(false)
let userList = ref<User[]>([])
let userSearchVO = reactive({keyword: '', pageNum: 1, pageSize: 10})

let computedUserId = computed({
  get: () => {
    return props.userId
  },
  set: (value) => {
    emits('update:userId', value)
  }
})
const loadUsers = (keyword: string) => {
  if (keyword) {
    //新的关键词需要重置 pageNum和finish
    if (keyword !== userSearchVO.keyword) {
      userSearchVO.pageNum = 1
      finish.value = false
      userList.value = []
    }
    userSearchVO.keyword = keyword
  }
  if (!finish.value) {
    loading.value = true
    listUser(userSearchVO).then(res => {
      if (res.list.length < userSearchVO.pageSize) {
        finish.value = true
      }
      loading.value = false
      userList.value.push(...res.list)
      userSearchVO.pageNum++
    })
  }
}
</script>

<style scoped>

</style>